package com.xxl.controller.handler;
import java.util.HashMap;
import java.util.List;

import jakarta.validation.ConstraintDeclarationException;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.ProblemDetail;
import org.springframework.validation.ObjectError;
import org.springframework.validation.FieldError;
import org.springframework.http.HttpStatusCode;
import org.springframework.core.MethodParameter;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.validation.BindingResult;

import com.xxl.util.ResponseHandlerUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * 全局异常类
 * @author xxl
 * @date 2023/3/19
 */
@RestControllerAdvice
@Slf4j
public class ResponseHandler {
    @Resource
    ResponseHandlerUtil<Map<String,Object>> util = new ResponseHandlerUtil<>();
    @Resource
    ResponseHandlerUtil<String> util2 = new ResponseHandlerUtil<>();
    /**
     *  @ExceptionHandler和@ResponseStatus使用,如果处理到
     *  两者都是建议配合全局处理使用,两者都是捕捉到对应的异常.但是他们之间执行顺序 @ExceptionHandler > @ResponseStatus
     *  如果出现异常会先执行@ExceptionHandler的方法然后再执行@ResponseStatus,直到被捕捉到然后被处理
     *  可以配合使用,但仅限于你知道这个异常的状态码和异常对象.
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, Object> ExceptionHandler(MethodArgumentNotValidException exception) {
        HashMap<String, Object> map = new HashMap<>();
        HttpStatusCode statusCode = exception.getStatusCode();
         BindingResult bindingResult = exception.getBindingResult();
         log.error("HttpStatusCode="+statusCode);
         log.error("BindingResult="+bindingResult);
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return util.commonReturn(map,400);
    }
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> ExceptionHandler1(ConstraintViolationException exception) {
        return util2.commonReturn(exception.getMessage(), 500);
    }
}
